<template>
  <div class="intelligentWriting">
    <div class="domainIds">
      <span class="domainIds-left">指标体系</span>
      <el-select
        @change="debounceSearchPageData"
        v-model="searchForm.domainIds"
        placeholder="请选择指标体系"
        clearable
        filterable
        class="res-select"
      >
        <el-option
          v-for="item in domainList"
          :key="item.value"
          :label="item.label"
          :value="item.value"
        />
      </el-select>
    </div>

    <el-row :gutter="10">
      <el-col :span="6">
        <el-input
          v-model="searchForm.key"
          style="width: 100%"
          placeholder="请输入要查询的指标ID、指标名称"
          :prefix-icon="Search"
          @input="debounceSearchPageData"
          clearable
        />
      </el-col>
      <el-col :span="4">
        <el-select
          @change="debounceSearchPageData"
          v-model="searchForm.showFilter"
          placeholder="展示类型"
          clearable
        >
          <el-option
            v-for="item in SHOW_FILTER_OPTIONS"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-col>
      <el-col :span="4">
        <el-select
          @change="debounceSearchPageData"
          v-model="searchForm.sensitiveLevel"
          placeholder="重要程度"
          clearable
        >
          <el-option
            v-for="item in SENSITIVELEVEL_OPTIONS"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
       
      </el-col>
      <el-col :span="8" :offset="2" style="text-align: right">
        <el-button :disabled="isDeleteDisabled" :icon="Delete" @click.stop="handleBatchDel">批量删除</el-button>
      </el-col>
    </el-row>
    <div
      v-loading="loading"
      element-loading-text="正在加载..."
      class="loading-page"
      v-if="loading"
    />
    <PageEmpty 
      v-else-if="!tableData.length && !loading" :type="'2'" 
      :text1="'没有找到相关的数据'" 
      :text2="'当前搜索没有匹配到任何结果，请检查输入或尝试其他关键词'"
    />
    <app-table
      v-else
      class="mt-25"
      :otherHeight="32"
      :pageLoading="loading"
      :data="tableData"
      :pagination-config="paginationConfig"
      @sizeChange="handleSizeChange"
      @changePage="getPageData"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" />

      <el-table-column prop="name" label="指标" min-width="180">
        <template #default="{ row }">
          <AutoTooltip>
            {{ row.name }}
          </AutoTooltip>
        </template>
      </el-table-column>
      <el-table-column prop="bizName" label="英文名" min-width="180">
        <template #default="{ row }">
          <AutoTooltip>
            {{ row.bizName }}
          </AutoTooltip>
        </template>
      </el-table-column>
      <el-table-column prop="description" label="描述" min-width="180">
        <template #default="{ row }">
          <AutoTooltip>
            {{ row.description }}
          </AutoTooltip>
        </template>
      </el-table-column>
      <!-- <el-table-column prop="status" label="状态" min-width="60">
        <template #default="{ row }">
          <AutoTooltip>
            {{ row.status === 1 ? '启用' : '禁用' }}
          </AutoTooltip>
        </template>
      </el-table-column> -->
      <el-table-column prop="sensitiveLevel" label="重要程度" min-width="80">
        <template #default="{ row }">
          <AutoTooltip>
            <el-tag 
              v-if="typeof row.sensitiveLevel === 'number' && !isNaN(row.sensitiveLevel) && SENSITIVELEVEL[row.sensitiveLevel] !== undefined" 
              :type="SENSITIVELEVELTagType[row.sensitiveLevel]"
              >
              {{ SENSITIVELEVEL[row.sensitiveLevel] }}
            </el-tag>
          </AutoTooltip>
        </template>
      </el-table-column>
      <el-table-column prop="createdBy" label="创建人" min-width="100">
        <template #default="{ row }">
          <AutoTooltip>
            {{ row.createdBy }}
          </AutoTooltip>
        </template>
      </el-table-column>
      <el-table-column prop="updatedAt" label="更新时间" min-width="130">
        <template #default="{ row }">
          <AutoTooltip>
            {{ datetimeFormat(row.updatedAt) }}
          </AutoTooltip>
        </template>
      </el-table-column>

      <el-table-column label="操作" align="center" width="80" fixed="right">
        <template #default="{ row }">
          <div v-if="row.hasAdminRes">
            <span class="mr-10 primary-text cursor-pointer" @click="handleDel(row)">
              <el-icon><Delete /></el-icon>
            </span>
          </div>
        </template>
      </el-table-column>
    </app-table>
  </div>
</template>

<script lang="ts" setup>
import AppTable from '@/components/app-table/index.vue'
import AutoTooltip from '@/components/auto-tooltip/index.vue'
import { MsgConfirm, MsgSuccess, MsgWarning } from '@/utils/message'
import { debounce } from 'lodash'
import { onMounted, reactive, ref } from 'vue'
import { Search, Delete } from '@element-plus/icons-vue'
import { SHOW_FILTER_OPTIONS, SENSITIVELEVEL_OPTIONS, SENSITIVELEVEL, SENSITIVELEVELTagType } from '@/enums/chatbi'
import ChaiBi from '@/api/chatbi'
import { datetimeFormat } from '@/utils/time'
import useStore from '@/stores'


const { user } = useStore()


const domainList = ref<any>([]); /**主题域列表 */
const searchForm = ref({
  key: '', // input输入
  showFilter: '', //展示类型
  sensitiveLevel: '', // 重要程度
  domainIds: '', // 主题域
})
/** 分页信息 */
const paginationConfig = reactive({
  current_page: 1,
  page_size: 20,
  total: 0
})
const tableData = ref<any>([])
const ids = ref([]) /** 单选/全选 */
const loading = ref(false)

const isDeleteDisabled = ref(true)

function handelDomainList() {
  ChaiBi.getDomainList().then((res:any)=> {
    if(res.data) {
      domainList.value = res.data.map((item:any) => {
        return {
          value: item.id,
          label: item.name
        }
      })
    }
  })
}

function handleDel(row: any) {
  MsgConfirm('提示', '确认删除选中数据吗？').then(() => {
    const data = {ids: [ row.id ], status: 3}
    ChaiBi.batchUpdateStatus(data).then((res: any) => {
      if(res.data) {
        MsgSuccess('删除成功！')
        getPageData()
      }
    })
  })
}

function handleSizeChange() {
  paginationConfig.current_page = 1
  getPageData()
}
function handleSelectionChange(val:any) {
  const hasAdmin = val.every((el: any) => el.hasAdminRes)
  if(!hasAdmin) {
    MsgWarning('您所选择的数据中包含有无权限的数据，请勿删除！')
    isDeleteDisabled.value = true;
    return
  }
  isDeleteDisabled.value = false;
  ids.value = val.map((v: any) => v.id)
}
function handleBatchDel() {
  if (ids.value.length === 0) {
    return MsgWarning('请先选择一条或多条数据!')
  }
  MsgConfirm('提示', '确认删除选中数据吗？').then(() => {
    const data = {ids: [ ...ids.value ], status: 3}
    ChaiBi.batchUpdateStatus(data).then((res: any) => {
      if(res.data) {
        MsgSuccess('删除成功！')
        getPageData()
        ids.value  = []
      }
    })
  })
}

const debounceSearchPageData = debounce(handleSizeChange, 300)

function getParam() {
  const { domainIds, key, sensitiveLevel, showFilter } = searchForm.value
  let params:any = { 
    createdBy: null,
    isPublish: 1,
    current: paginationConfig.current_page,
    pageSize: paginationConfig.page_size,
    total: 0,
  }
  if (domainIds) params.domainIds = [domainIds] || []
  if( key)  params.key = key
  if(sensitiveLevel && sensitiveLevel !== 'all') {
    params.sensitiveLevel = Number(sensitiveLevel)
  }
  if(showFilter && showFilter !== 'all') {
    // onlyShowMe: true我创建的  hasCollect: true 我的收藏
    if(showFilter === 'onlyShowMe') {
      params.onlyShowMe = true
      params.showFilter = ['onlyShowMe']
      params.createdBy = user?.userInfo?.name || null
    }
    if(showFilter === 'hasCollect') {
      params.hasCollect = true
      params.showFilter = ['hasCollect']
    }
  }

  return params
}
function getPageData() {
  const param = getParam()
  loading.value = true
  ChaiBi.queryMetric(param).then((res) => {
    if (res.data.list.length > 0) {
      const { total, list, pageSize, pageNum } = res.data
      tableData.value = list
      paginationConfig.total = total
      paginationConfig.current_page = pageNum
      paginationConfig.page_size = pageSize
    } else {
      tableData.value = []
      paginationConfig.total = 0
      paginationConfig.current_page = 1
    }
  }).finally(() => {
    loading.value = false
  })
}

onMounted(() => {
  /* 获取主题域*/
  handelDomainList();
  /** 获取列表数据 */
  getPageData()
})
</script>

<style scoped lang="scss">
.card {
  background: rgba(229, 237, 255, 0.41);
  padding-top: 16px;
  padding-bottom: 17px;
  padding-left: 20px;
  position: relative;
  cursor: pointer;
  border-radius: 8px 8px 8px 8px;
  p {
    font-weight: 500;
    font-size: 18px;
    color: #333333;
    line-height: 22px;
    text-align: left;
    font-style: normal;
    text-transform: none;
  }
  span {
    font-weight: 400;
    font-size: 12px;
    color: #666666;
    line-height: 14px;
    text-align: left;
    font-style: normal;
    text-transform: none;
    margin-top: 9px;
  }
  img {
    position: absolute;
    right: 10px;
    top: 10px;
  }
}
.domainIds{
  display: flex;
  width: 300px;
  justify-content: center;
  align-items: center;
  position: absolute;
  top: 65px;
  margin-left: -26px;
  .domainIds-left{
     width: 80px;
  }
}
.cursor-pointer{
  cursor: pointer;
}

.loading-page {
  width: calc(100vw - 200px);
  height: calc(100vh - 180px);
  position: absolute !important;
  margin-left: -20px;
  bottom: 0;
}
</style>
